<!-- 「礼品详情」页面 -->
<template>
  <!-- 导航栏 -->
  <uni-nav-bar
    class="nav-bar"
    fixed="true"
    title="礼品详情"
    status-bar="true"
    :border="false"
    left-icon="left"
    @click-left="back"
  />
  <!-- 详情图片 -->
  <image
    :src="detailImg"
    mode="widthFix"
    style="width: 100vw;"
  />
  <!-- 底部兑换栏 -->
  <div class="bottom-bar">
    <div
      class="redeem-btn"
      :class="btnClass"
      @click="exchangeBtnClick(giftId)"
    >
      <image
        v-if="!isExchangedCourse"
        class="miaodou-icon"
        src="@/static/icons/common/miaodou.png"
      />
      <text class="price">
        {{ isExchangedCourse ? '' : giftPrice }}
      </text>
      <text class="text">
        {{ btnText }}
      </text>
    </div>
  </div>
  <!-- 兑换成功弹窗 -->
  <RedeemSuccessPopup
    ref="redeemSuccessPop"
    :gift-id="redeemSuccessGiftId"
    :desc="redeemSuccessDesc"
    :gift-img="redeemSuccessGiftImg"
    :gift-name="redeemSuccessGiftName"
  />
</template>

<script lang="ts" setup>
import RedeemSuccessPopup from '@/components/RedeemSuccessPopup.vue';
import { useActivity618 } from '@/stores/activity-618-store';
import { useUser } from '@/stores/user';
import { back, navigateTo } from '@/utils/navigate';
import { showToast } from '@/utils/tools';

const userStore = useUser();
const { miaodouStatus } = storeToRefs(userStore);
const { getInfo } = userStore;

const activity618Store = useActivity618();
const { getGiftList, redeemGift } = activity618Store;
const { giftList } = storeToRefs(activity618Store);

/** 当前组件实例 */
const currentInstance = getCurrentInstance();

// #region 详情图片相关

/** 礼物id */
const giftId = ref('');

/** 礼物信息 */
const giftInfo = computed(() => giftList.value.find((item) => item.id === giftId.value));

// #region 内容展示相关

/** 礼物价格 */
const giftPrice = computed(() => giftInfo.value?.price || 0);

/** 详情图片 */
const detailImg = computed(() => giftInfo.value?.detailImg || '');

onLoad(async (options) => {
  giftId.value = options?.giftId || '';
  if (!giftList.value.length) {
    await getGiftList();
  }
});

// #endregion

// #region 兑换按钮、兑换成功弹窗相关

/** 是否已兑换课程 */
const isExchangedCourse = computed(() => {
  /** 课程id */
  const { courseId } = giftInfo.value || {};

  // 如果有课程id，且已经兑换过，则返回true
  if (courseId && giftInfo.value?.isExchanged) {
    return true;
  }

  return false;
});

/** 按钮文本 */
const btnText = computed(() => {
  // 如果已经兑换了课程，则返回「课程详情」
  if (isExchangedCourse.value) return '课程详情';

  // 否则根据是否已经兑换过显示「兑换」或「已兑换」
  return giftInfo?.value?.isExchanged ? '已兑换' : '兑换';
});

/** 按钮class */
const btnClass = computed(() => {
  // 如果已经兑换了课程，则不置灰
  if (isExchangedCourse.value) return '';

  // 否则根据是否已经兑换过进行置灰
  return giftInfo?.value?.isExchanged ? 'disabled' : '';
});

/**
 * 「兑换」按钮点击事件
 * @param giftId 礼品 ID
 */
const exchangeBtnClick = async (giftId: string) => {
  console.log(giftInfo.value);

  // 判断按钮文本是否是「课程详情」
  if (btnText.value === '课程详情') {
    navigateTo('CourseDetail', { courseId: giftInfo.value?.courseId || '' });
    return;
  }
  // 判断喵豆是否足够
  const targetGift = giftList.value?.find((item) => item?.id === giftId);
  if (miaodouStatus.value.availableMiaodou < (targetGift?.price || 0)) {
    showToast('当前喵豆不足');
    return;
  }

  // 判断是否已经兑换过
  if (targetGift?.isExchanged) {
    showToast('不可重复兑换同一件商品');
    return;
  }

  // 判断礼品是否已兑换完
  if ((targetGift?.stockNum || 0) <= 0) {
    showToast('您来晚了，该奖品已兑换完了');
    return;
  }

  const giftName = giftList.value.find((item) => item.id === giftId)?.name;
  const content = `是否确定兑换${giftName}？`;
  uni.showModal({
    content,
    success: async (res) => {
      if (res.confirm) {
        await toRedeemGift(giftId);
      }
    },
  });
};

/**
 * 尝试兑换礼品
 * @param giftId 礼品 ID
 */
const toRedeemGift = async (giftId: string) => {
  const code: Code = await redeemGift(giftId);
  console.log('code', code);
  switch (code) {
    case '200':
      toggleRedeemSuccessPop(true);
      redeemSuccessGiftId.value = giftId;
      const redeemSuccessGift = giftList.value.find((item) => item.id === giftId);
      console.log('redeemSuccessGift', redeemSuccessGift);
      redeemSuccessGiftImg.value = redeemSuccessGift?.img || '';
      redeemSuccessGiftName.value = redeemSuccessGift?.name || '';
      redeemSuccessDesc.value = redeemSuccessGift?.successDesc || '';
      break;
    case '201':
      showToast('提示：喵豆不足，快去赚喵豆吧');
      break;
    case '202':
      showToast('不可重复兑换同一件商品');
      break;
    case '203':
      showToast('您来晚了，该奖品已兑换完了');
      break;
  }
  // 更新礼物信息和喵豆信息
  getGiftList();
  getInfo();
};

/** 兑换成功的礼品的id */
const redeemSuccessGiftId = ref('');

/** 兑换成功说明 */
const redeemSuccessDesc = ref('');

/** 兑换成功礼品图片 */
const redeemSuccessGiftImg = ref('');

/** 兑换成功礼品名称 */
const redeemSuccessGiftName = ref('');

/**
 * 切换弹窗显示与否
 * @param isShow 是否显示
 */
const toggleRedeemSuccessPop = (isShow: boolean) => {
  const redeemSuccessPop = currentInstance?.refs.redeemSuccessPop as any;
  console.log('redeemSuccessPop', redeemSuccessPop);

  if (isShow) {
    redeemSuccessPop?.open();
  } else {
    redeemSuccessPop?.close();
  }
};

// #endregion

</script>

<style lang="scss" scoped>
// 底部兑换栏
.bottom-bar {
  position: fixed;
  bottom: -5px;
  left: 0;
  z-index: 100;

  width: 100vw;
  height: 14.8718vw;

  background-color: #fff;

  padding-bottom: constant(safe-area-inset-bottom);

  /* 兼容 IOS<11.2 */
  padding-bottom: env(safe-area-inset-bottom);

  /* 兼容 IOS>11.2 */
  box-sizing: content-box;
  display: flex;
  justify-content: center;

  .redeem-btn {
    margin-top: 8px;

    width: 87.6923vw;
    height: 10.7692vw;

    background: linear-gradient(90deg, #FF3C43, #FF9502 100%);
    border-radius: 4px;

    display: flex;
    align-items: center;
    justify-content: center;

    // 禁用状态
    &.disabled {
      background: #e5e5e5;

      color: #999;
    }

    .miaodou-icon {
      width: 4.6154vw;
      height: 4.6154vw;
    }

    .price {
      margin-left: 0.7692vw;

      font-size: 4.359vw;
      color: #fff;
    }

    .text {
      margin-left: 4px;

      font-size: 4.1026vw;
      color: #fff;
    }
  }
}
</style>
